<?php


namespace BeReborn\Http;


use BeReborn\Base\Component;
use Swoole\Coroutine\Client;

/**
 * Class Grpc
 * @package BeReborn\Http
 */
class Grpc extends Component
{

	/** @var Grpc */
	private static $_instance;

	private $_host = '127.0.0.1';
	private $_port = '33007';

	/**
	 * @return Grpc
	 */
	public static function getInstance()
	{
		if (static::$_instance instanceof Grpc) {
			return static::$_instance;
		}
		return static::$_instance = new Grpc();
	}

	/**
	 * @param $host
	 */
	public function setHost($host)
	{
		$this->_host = $host;
	}

	/**
	 * @param $port
	 */
	public function setPort($port)
	{
		$this->_port = $port;
	}

	/**
	 * @param string $route
	 * @param array $data
	 * @param array $header
	 * @return bool|mixed
	 */
	public function request(string $route, array $data = [], array $header = [])
	{
		$client = new Client(SWOOLE_TCP);
		if (!$client->connect($this->_host, $this->_port)) {
			return false;
		}
		$client->send($this->serialize($route, $data, $header));
		$recv = $client->recv();
		$client->close();
		return $recv;
	}

	/**
	 * @param $route
	 * @param $data
	 * @param $header
	 * @return mixed
	 */
	private function serialize($route, $data, $header)
	{
		$param = [
			'route'  => $route,
			'header' => $header,
			'body'   => $data
		];
		return \swoole_serialize::pack($param);
	}

}
